package net.zhengxinyun.performance.service.indicators;

import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.data.TownScoreData;
import net.zhengxinyun.performance.entity.TownIndicatorsEntity;
import net.zhengxinyun.performance.entity.TownScoreEntity;
import net.zhengxinyun.performance.filter.TownFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.filter.TownScoreFilter;
import net.zhengxinyun.performance.mapper.Indicators.TownIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownScoreEntityMapper;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Created by hyp1202 on 2018/11/22.
 */
@Service
public class TownScoreServiceImpl implements TownScoreService {

    @Value("${path}")
    public  String PATH ;

    private TownIndicatorsEntityMapper townIndicatorsEntityMapper;

    private TownMapper townMapper;

    private TownScoreEntityMapper townScoreEntityMapper;

    @Autowired
    private TownScoreData townScoreData;

    @Autowired
    public TownScoreServiceImpl(TownIndicatorsEntityMapper townIndicatorsEntityMapper, TownMapper townMapper, TownScoreEntityMapper townScoreEntityMapper) {
        this.townIndicatorsEntityMapper = townIndicatorsEntityMapper;
        this.townMapper = townMapper;
        this.townScoreEntityMapper = townScoreEntityMapper;
    }

    @Override
    public List<Map<String, Object>> query(TownIndicatorsFilter townIndicatorsFilter) {
        if ("4".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit("");
        }
        List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.queryScoreByIndexId(townIndicatorsFilter);
        List<Map<String, Object>> indexList = new ArrayList<>();
        TownIndicatorsEntity entity;
        for (TownIndicatorsFilter filter : list) {
            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", filter.getId());
            indexMap.put("indexType", filter.getIndexType());
            indexMap.put("leadUnit", filter.getLeadUnit());
            indexMap.put("indexName", filter.getIndexName());
            indexMap.put("responsibilityUnit", filter.getResponsibilityUnit());
            indexMap.put("direction", filter.getDirection());
            indexMap.put("audit",filter.getAudit());
            indexMap.put("monthTime",filter.getMonthTime());
            indexMap.put("reason",filter.getReason());
            indexMap.put("mainUnit",filter.getMainUnit());
            if (StringUtils.isNotBlank(filter.getWeight())) {
                indexMap.put("weight", Double.parseDouble(filter.getWeight()));
            } else {
                indexMap.put("weight", null);
            }
            indexMap.put("dateTime", filter.getDateTime());
            //把对应的上级指标名返回给前端
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }
            List<TownFilter> townList = townMapper.queryTownAndScore(filter.getId().toString());
            Map<String, Object> townMap = new HashMap<>();
            for (TownFilter townFilter : townList) {
                if ("0".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getWeight()));
                } else if ("1".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getScore()));
                } else if ("2".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getFinalScore()));
                } else if ("3".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getRank()));
                } else if ("4".equals(townIndicatorsFilter.getScoreType())) {
                    Map<String, Object> map = new HashMap<>();
                    if (StringUtils.isNotBlank(townFilter.getWeight())){
                        map.put("weight", Util.doubleParse(townFilter.getWeight()));
                    }else {
                        map.put("weight", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getScore())){
                        map.put("score",Util.doubleParse( townFilter.getScore()));
                    }else {
                        map.put("score",null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getFinalScore())) {
                        map.put("finalScore", Util.doubleParse(townFilter.getFinalScore()));
                    } else {
                        map.put("finalScore", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getRank())){
                        map.put("rank", Util.doubleParse(townFilter.getRank()));
                    }else {
                        map.put("rank",null);
                    }
                    townMap.put(townFilter.getTownName(), map);
                }
            }
            if (townMap.size() != 0) {
                indexMap.put("townList", townMap);
            }
            indexList.add(indexMap);
        }
        return indexList;
    }

    /**
     * 获取指标，乡镇，得分这三个值的总页数
     *
     * @param townIndicatorsFilter
     * @return
     */
    public Integer getThreeTableCount(TownIndicatorsFilter townIndicatorsFilter) {
        return townIndicatorsEntityMapper.getThreeTableCount(townIndicatorsFilter);
    }

    /**
     * 设置个乡镇分数
     *
     * @param townIndicatorsFilter
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String setScore(TownIndicatorsFilter townIndicatorsFilter, List<TownIndicatorsFilter> list) {
        TownFilter townFilter = new TownFilter();
        TownScoreEntity townScoreEntity = new TownScoreEntity();
        TownScoreFilter townScoreFilter = new TownScoreFilter();
        Iterator<TownIndicatorsFilter> iterator = list.iterator();
        //如果乡镇权数是0则去掉
        while (iterator.hasNext()){
            TownIndicatorsFilter filter = iterator.next();
            if ("0".equals(filter.getWeight())){
                iterator.remove();
                continue;
            }
            if (StringUtils.isBlank(filter.getScore())){
                return filter.getTownName()+"没有设置分数";
            }
        }
        Collections.sort(list, new Comparator<TownIndicatorsFilter>() {
            @Override
            public int compare(TownIndicatorsFilter o1, TownIndicatorsFilter o2) {
                if (Double.parseDouble(o1.getScore())<Double.parseDouble(o2.getScore())){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        int rank = 1;
        for (TownIndicatorsFilter filter : list) {
            townFilter.setIndexId(filter.getId().toString());
            townFilter.setTownName(filter.getTownName());
            String id = townMapper.queryId(townFilter).toString();
            townScoreEntity.setIndexId(filter.getId().toString());
            townScoreEntity.setTownId(id);
            townScoreFilter.setIndexId(filter.getId().toString());
            townScoreFilter.setTownId(id);
            townScoreEntity.setMonthTime(filter.getMonthTime());
            townScoreEntity.setRank(rank+"");
            if (StringUtils.isNotBlank(filter.getScore()) && Double.parseDouble(filter.getScore()) <= 100) {
                townScoreEntity.setScore(filter.getScore());
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return filter.getTownName() + "分数输入有误";
            }
            List<TownScoreFilter> filterList = townScoreEntityMapper.query(townScoreFilter);
            //判断数据库是否已有该指标乡镇得分数据，如果有并且审核状态为待审核，则修改该数据
            if (filterList.size() != 0) {
                if ("0".equals(filterList.get(0).getAudit()) || "3".equals(filterList.get(0).getAudit())){
                    townScoreEntity.setAudit("0");
                    townScoreEntity.setReason("");
                    int t = townScoreEntityMapper.updateByIndexIdAndTownId(townScoreEntity);
                    if (t == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "设置" + filter.getTownName() + "失败请重试";
                    }
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "该指标已审核无法修改";
                }
            } else {
                townScoreEntity.setAudit("0");
                int i = townScoreEntityMapper.insert(townScoreEntity);
                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "设置" + filter.getTownName() + "失败请重试";
                }
            }
            rank++;
        }
        return "操作成功";
    }

    /**
     * 管理员批量通过，通过townFilter集合传对应的乡镇id和月份确定是审核的哪些乡镇，在根据sql语句直接修改
     *
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String auditAllPass(List<TownIndicatorsFilter> list) {
        for (TownIndicatorsFilter townIndicatorsFilter : list) {
            List<TownFilter> townList = townMapper.queryByIndexId(townIndicatorsFilter.getId().toString());
            TownScoreEntity townScoreEntity = new TownScoreEntity();
            TownScoreFilter filter = new TownScoreFilter();
            for (TownFilter townFilter : townList) {
                townScoreEntity.setTownId(townFilter.getId().toString());
                townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
                filter.setTownId(townFilter.getId().toString());
                filter.setMonthTime(townIndicatorsFilter.getMonthTime());
                List<TownScoreFilter> filterList = townScoreEntityMapper.query(filter);
                if (CollectionUtils.isEmpty(filterList)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "数据有误，请联系管理员";
                }
                if (!"1".equals(filterList.get(0).getAudit())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "未到管理员审核阶段，请重新审核";
                }
                townScoreEntity.setAudit("2");
                townScoreEntity.setFinalScore(Util.getFinalScore(filterList.get(0).getScore(),townFilter.getWeight()));
                int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "审核通过失败";
                }
            }
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String responsibleAllPass(List<TownIndicatorsFilter> list) {
        for (TownIndicatorsFilter townIndicatorsFilter : list) {
            List<TownFilter> townList = townMapper.queryByIndexId(townIndicatorsFilter.getId().toString());
            TownScoreEntity townScoreEntity = new TownScoreEntity();
            TownScoreFilter filter = new TownScoreFilter();
            for (TownFilter townFilter : townList) {
                townScoreEntity.setTownId(townFilter.getId().toString());
                townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
                filter.setTownId(townFilter.getId().toString());
                filter.setMonthTime(townIndicatorsFilter.getMonthTime());
                List<TownScoreFilter> filterList = townScoreEntityMapper.query(filter);
                if (CollectionUtils.isEmpty(filterList)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "数据有误，请联系管理员";
                }
                if (!"0".equals(filterList.get(0).getAudit())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "未到责任人审核阶段，请重新审核";
                }
                townScoreEntity.setAudit("1");
                int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "审核通过失败";
                }
            }
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String noPass(TownIndicatorsFilter townIndicatorsFilter) {
        if (StringUtils.isBlank(townIndicatorsFilter.getReason())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "回退原因不能为空";
        }
        TownScoreEntity townScoreEntity = new TownScoreEntity();
        TownScoreFilter townScoreFilter = new TownScoreFilter();
        townScoreFilter.setIndexId(townIndicatorsFilter.getId().toString());
        townScoreFilter.setMonthTime(townIndicatorsFilter.getMonthTime());
        List<TownScoreFilter> list = townScoreEntityMapper.query(townScoreFilter);
        for (TownScoreFilter filter:list) {
            townScoreEntity.setAudit("3");
            townScoreEntity.setReason(townIndicatorsFilter.getReason());
            townScoreEntity.setTownId(filter.getTownId());
            townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
            int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "审核通过失败";
            }
        }
        return "操作成功";
    }

    @Override
    public List<Map<String, Object>> queryForAudit(TownIndicatorsFilter townIndicatorsFilter) {
        if ("4".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit("");
        }
        List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.queryScoreForAudit(townIndicatorsFilter);
        List<Map<String, Object>> indexList = new ArrayList<>();
        TownIndicatorsEntity entity;
        for (TownIndicatorsFilter filter : list) {
            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", filter.getId());
            indexMap.put("indexType", filter.getIndexType());
            indexMap.put("leadUnit", filter.getLeadUnit());
            indexMap.put("indexName", filter.getIndexName());
            indexMap.put("responsibilityUnit", filter.getResponsibilityUnit());
            indexMap.put("direction", filter.getDirection());
            indexMap.put("audit",filter.getAudit());
            indexMap.put("monthTime",filter.getMonthTime());
            indexMap.put("reason",filter.getReason());
            indexMap.put("mainUnit",filter.getMainUnit());
            if (StringUtils.isNotBlank(filter.getWeight())) {
                indexMap.put("weight", Double.parseDouble(filter.getWeight()));
            } else {
                indexMap.put("weight", null);
            }
            indexMap.put("dateTime", filter.getDateTime());
            //把对应的上级指标名返回给前端
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }
            List<TownFilter> townList = townMapper.queryTownAndScore(filter.getId().toString());
            Map<String, Object> townMap = new HashMap<>();
            for (TownFilter townFilter : townList) {
                if ("0".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getWeight()));
                } else if ("1".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getScore()));
                } else if ("2".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getFinalScore()));
                } else if ("3".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getRank()));
                } else if ("4".equals(townIndicatorsFilter.getScoreType())) {
                    Map<String, Object> map = new HashMap<>();
                    if (StringUtils.isNotBlank(townFilter.getWeight())){
                        map.put("weight", Util.doubleParse(townFilter.getWeight()));
                    }else {
                        map.put("weight", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getScore())){
                        map.put("score",Util.doubleParse( townFilter.getScore()));
                    }else {
                        map.put("score",null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getFinalScore())) {
                        map.put("finalScore", Util.doubleParse(townFilter.getFinalScore()));
                    } else {
                        map.put("finalScore", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getRank())){
                        map.put("rank", Util.doubleParse(townFilter.getRank()));
                    }else {
                        map.put("rank",null);
                    }
                    townMap.put(townFilter.getTownName(), map);
                }
            }
            if (townMap.size() != 0) {
                indexMap.put("townList", townMap);
            }
            indexList.add(indexMap);
        }
        return indexList;
    }

    public int getAuditCount(TownIndicatorsFilter townIndicatorsFilter){
        return townIndicatorsEntityMapper.getAuditCount(townIndicatorsFilter);
    }

    @Override
    @Transactional
    public String setFirstFinalScore(TownIndicatorsFilter townIndicatorsFilter) {
        TownIndicatorsEntity indicatorsEntity = townIndicatorsEntityMapper.selectByPrimaryKey(townIndicatorsFilter.getId());
        indicatorsEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
        if (townIndicatorsEntityMapper.queryNullFinal(indicatorsEntity) == 0){
            Double finalScore = townIndicatorsEntityMapper.queryFirstFinalScore(indicatorsEntity);
            TownScoreEntity entity = new TownScoreEntity();
            entity.setIndexId(indicatorsEntity.getSuperiorIndexId());
            entity.setMonthTime(townIndicatorsFilter.getMonthTime());
            entity.setDateTime(indicatorsEntity.getDateTime());
            entity.setFinalScore(finalScore.toString());
            entity.setAudit("2");
            int i  = townScoreEntityMapper.insert(entity);
            if (i == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "一级指标得分设置失败";
            }
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "还没够";
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String importTownScore(MultipartFile file) {
        if (file.getOriginalFilename().endsWith(".xls")  && file.getOriginalFilename().endsWith(".xlsx")) {
            return "文件后缀不对";
        }
        String filePath;
        try {
            Util.write(file.getOriginalFilename(), file.getInputStream());
            filePath = this.PATH + file.getOriginalFilename();
            filePath = new String(filePath.getBytes("utf-8"), "utf-8");
            if (com.sirdc.modules.utils.StringUtils.isBlank(filePath)) {
                return "filePath为空";
            }
            List<List<TownScoreEntity>> lists = townScoreData.importTownScore(filePath);
            for (List<TownScoreEntity> list:lists) {
                for (TownScoreEntity entity:list) {
                    int i = townScoreEntityMapper.insert(entity);
                    if (i == 0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "导入失败！";
                    }
                }
            }
            return "导入成功";
        }catch (Exception e){
            return "导入失败!";
        }
    }

    @Override
    public String update(TownScoreEntity townScoreEntity) {
        return null;
    }

    @Override
    public String insert(TownScoreEntity townScoreEntity) {
        return null;
    }

    @Override
    public String delete(TownScoreEntity townScoreEntity) {
        return null;
    }
}
